<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <!-- v-model中收集的值是 el-tab-pane中name属性的值 -->
        <!-- tab-click:当你点击了某一个页签的时候 就会触发该事件 -->
        <el-tabs>
          <!-- 左侧 -->
          <el-tab-pane label="角色管理">
            <!-- 按钮 -->
            <el-button
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click="showAddRoleDialog"
            >新增角色</el-button>
            <!-- 表格 -->
            <el-table v-loading="isLoading" :data="list">
              <el-table-column label="序号" width="100" type="index" :index="indexMethod" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success" @click="assignRole(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRole(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRole(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- current-page表示的当前页 -->
            <!-- page-sizes:供我们下拉选择的页容量 -->
            <!-- pagesize:表示当前页容量（一般和page-sizes数组中的第一个值是对应的） -->
            <!-- layout：表示分页的样式展示 -->
            <!-- total表示的是一共有多少条数据 -->
            <!-- @size-change：当每页页容量发生变化时触发 -->
            <!-- @current-change ：页码发生变化时触发 -->
            <div class="pager" style="margin:10px;display:flex;justify-content:flex-end">
              <el-pagination
                :current-page="page"
                :page-sizes="[2, 4, 6, 8, 10]"
                :page-size="pagesize"
                layout="total,sizes,prev,pager,next,jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-tab-pane>

          <el-tab-pane label="公司信息">
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <el-dialog :title="showTitle" :visible="showDialog" :close-on-click-modal="false" @close="closeDialog">
        <el-form ref="roleForm" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="form.description" placeholder="请输入角色描述" />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="confirmAddRole">确认</el-button>
        </template>
      </el-dialog>
      <!-- 分配权限的弹层 -->
      <el-dialog title="分配权限" :visible="showAssignDialog" :close-on-click-modal="false" @open="getPermissionList" @close="closeAssignDialog">
        <el-tree
          ref="tree"
          node-key="id"
          :data="permissionList"
          show-checkbox
          default-expand-all
          :check-strictly="true"
          :props="{label:'name'}"
        />
        <template #footer>
          <div style="text-align: right;">
            <el-button @click="closeAssignDialog">取消</el-button>
            <el-button type="primary" @click="confirmAssignRole">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRoleListApi, delRoleApi, addRoleApi, getRoleDetailApi, updateRoleApi, assignPermApi } from '@/api/settings'
import { getCompanyByIdApi } from '@/api/company'
import { getPermissionListApi } from '@/api/permission'
import { mapState } from 'vuex'
import { transListToTreeData } from '@/utils/index'
export default {
  name: 'Setting',
  data() {
    return {
      page: 1,
      pagesize: 2,
      // 当前页的数据
      list: [],
      // 总条数
      total: 0,
      isLoading: false,
      showDialog: false,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称不可为空', trigger: 'blur' }
        ]
      },
      companyForm: {
        name: '',
        companyAddress: '',
        mailbox: '',
        remarks: ''
      },
      showAssignDialog: false,
      permissionList: [],
      // 用户原有权限
      permIds: [],
      // 点击分配时的角色id
      roleId: ''
    }
  },
  computed: {
    ...mapState('user', ['userInfo']),
    showTitle() {
      return this.form.id ? '编辑角色' : '添加角色'
    }
  },
  created() {
    this.getRoleList()
    this.getCompanyById()
  },
  methods: {
    /**
     * 确认分配权限
     */
    async confirmAssignRole() {
      const checkIdList = this.$refs.tree.getCheckedKeys()
      await assignPermApi({ id: this.roleId, permIds: checkIdList })
      this.$message.success('恭喜！权限分配成功')
      this.closeAssignDialog()
    },
    /**
     * 获取权限列表
     */
    async getPermissionList() {
      const { data } = await getPermissionListApi()
      this.permissionList = transListToTreeData(data, '0')
    },
    /**
     * 关闭分配权限的弹框
     */
    closeAssignDialog() {
      this.showAssignDialog = false
    },
    /**
     * 点击分配权限
     */
    async assignRole(id) {
      this.showAssignDialog = true
      this.roleId = id
      const { data: { permIds }} = await getRoleDetailApi(id)
      this.permIds = permIds
      this.$refs.tree.setCheckedKeys(permIds)
    },
    /**
     * 获取公司信息
     */
    async getCompanyById() {
      const { data } = await getCompanyByIdApi(this.userInfo.companyId)
      this.companyForm = data
    },
    /**
     * 点击了编辑按钮
     */
    async editRole(id) {
      const { data } = await getRoleDetailApi(id)
      this.form = data
      this.showDialog = true
    },
    /**
     * 确定添加
     */
    confirmAddRole() {
      this.$refs.roleForm.validate(async flag => {
        if (!flag) return
        if (this.form.id) {
          await updateRoleApi(this.form)
          this.$message.success('恭喜！编辑成功')
        } else {
          await addRoleApi(this.form)
          this.$message.success('恭喜！添加成功')
        }
        this.closeDialog()
        this.getRoleList()
      })
    },
    /**
     * 打开添加角色的弹框
     */
    showAddRoleDialog() {
      this.showDialog = true
    },
    /**
     * 关闭添加角色的弹框
     */
    closeDialog() {
      this.showDialog = false
      this.$refs.roleForm.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    /**
     * 删除角色
     */
    delRole(id) {
      this.$confirm('亲！您确定要删除该角色吗？', '温馨提示').then(async() => {
        // 用户点击了确定
        await delRoleApi(id)
        this.$message.success('删除成功')
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        this.getRoleList()
      }).catch(() => {})
    },
    /**
     * 计算当前行的行号
     */
    indexMethod(index) {
      return (this.page - 1) * this.pagesize + index + 1
    },
    /**
     * 页容量变化
     */
    handleSizeChange(val) {
      this.pagesize = val
      this.page = 1
      this.getRoleList()
    },
    /**
     * 页码变化
     */
    handleCurrentChange(val) {
      this.page = val
      this.getRoleList()
    },
    /**
     * 获取角色列表
     */
    async getRoleList() {
      this.isLoading = true
      const { data } = await getRoleListApi(this.page, this.pagesize)
      this.list = data.rows
      this.total = data.total
      this.isLoading = false
    }
  }
}
</script>

<style>
</style>
